<?php
namespace app\api\controller;

use app\api\model\Clue as ApiClueModel;
use app\common\model\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use think\Db;
use think\Queue;
use think\Request;

// 快手接收线索接口
// 成功返回 code：0
// 请求header参数token：2QKr4YOU19doHgJt
// 请求域名：https://www.fengzhu.top/api/kuaishou/clue_accept POST JSON
class AcceptclueKuaiShou
{
    // 定义请求接口时Header中携带参数的名称和值
    const TOKEN = "3QKr4YOU19doHgJt";

    public $is_check_repeat = true; // 是否检查撞库

    // 接收线索
    public function accept()
    {
        if (Request::instance()->header('token') != self::TOKEN) {
            return Json(['msg' => '非法请求', 'status' => 200, "code" => 500]);
        }

        $post = \input('post.');
        if (empty($post)) {
            return Json(['msg' => '请求参数有误', 'status' => 200, "code" => 500]);
        }
        writelog("请求参数:" . json_encode($post, JSON_UNESCAPED_UNICODE), 'kuaishou');

        $postData = $post;
        $isAid = Db::name('account')->where('adv_id', $postData['adv_id'])->find();
        if (empty($isAid)) {
            return Json(['msg' => '账户有误', 'status' => 200, "code" => 500]);
        }
        if ($isAid['status'] != 1) {
            return Json(['msg' => '账户已禁用', 'status' => 200, "code" => 500]);
        }

        $this->is_check_repeat = $isAid['is_check_repeat'] == 1; // 账户是否设置进线重复提示

        $aid = $isAid['adv_id'];
        $insertLog = [
            'api_url' => $isAid['acc_name'] ?? "",
            'adv_id' => $aid,
            'phone' => isset($postData['mobile']) ? $postData['mobile'] : '',
            'name' => isset($postData['name']) ? $postData['name'] : '',
            'city' => isset($postData['city']) ? $postData['city'] : '',
            'param' => json_encode($_GET, JSON_UNESCAPED_UNICODE),
            'data' => json_encode($postData, JSON_UNESCAPED_UNICODE),
            'create_time' => date('Y-m-d H:i:s')
        ];
        $apiId = Db::name('clue_api_log')->insertGetId($insertLog);

        if (empty($postData['name'])) {
            ApiClueModel::setClueApiLogError($apiId, '姓名不能为空');
            return Json(['msg' => '姓名不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['mobile'])) {
            ApiClueModel::setClueApiLogError($apiId, '手机号不能为空');
            return Json(['msg' => '手机号不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['city'])) {
            ApiClueModel::setClueApiLogError($apiId, '城市不能为空');
            return Json(['msg' => '城市不能为空', 'status' => 200, "code" => 500]);
        }

        if (empty($postData['clue_id'])) {
            ApiClueModel::setClueApiLogError($apiId, '线索没有ID属性');
            return Json(['msg' => '线索没有ID属性', 'status' => 200, "code" => 500]);
        }

        $isClue = \db('clue')->where('clue_id', $postData['clue_id'])->find();
        if ($isClue) {
            ApiClueModel::setClueApiLogError($apiId, 'API线索接收失败，线索ID已存在');
            return Json(['msg' => 'API线索接收失败，线索ID已存在', 'status' => 200, "code" => 500]);
        }

        //优先级：房>车>公积金
        $pro_id = 5;
        //产品为车
        if (!empty($postData['form_name']) && strpos($postData['form_name'], "车") !== false) {
            $pro_id = 4;
        }
        //产品为房
        if (!empty($postData['form_name']) && strpos($postData['form_name'], "房") !== false) {
            $pro_id = 3;
        }

        if (!empty($postData['form_name']) && strpos($postData['form_name'], "公积金") !== false) {
            $pro_id = 6;
        }
        if (!empty($postData['form_name']) && strpos($postData['form_name'], "企业") !== false) {
            $pro_id = 7;
        }

        $params = $postData;
        $params['clue_id'] = $postData['clue_id'];
        $params['adv_id'] = $aid;
        $params['clue_name'] = $postData['name'];
        $params['phone'] = $postData['mobile'];
        $params['city'] = $postData['city'];
        $params['clue_city'] = $postData['clue_city'] ?? "";
        $params['apply_limit'] = isset($postData['apply_limit']) ? $postData['apply_limit'] : 0;
        $params['age'] = isset($postData['age']) ? $postData['age'] : 0;
        $params['gender'] = isset($postData['gender']) ? $postData['gender'] : 0;
        $params['pro_id'] = $pro_id;
        $params['ip'] = isset($postData['ip']) ? $postData['ip'] : get_client_ip();
        $params['type'] = $isAid['channel_id'];
        $params['create_time'] = time();
        $params['promotion_id'] = empty($params['promotion_id']) ? "" : $params['promotion_id'];

        // 详细信息 扩展字段
        $details=[];
        if (!empty($params['details']['form_details'])) {
            $car = [];
            $house = [];
            $public_funds = [];
            $company = [];
            foreach ($params['details']['form_details'] as $k => $v) {
                $details[]=['name'=>$v['key'],'value'=>$v['value']];


                if ($v['comp_type'] == '姓名' || $v['key'] == '姓名') {
                    $params['clue_name'] = $v['value'];
                }

                if ($v['comp_type'] == '电话' || $v['key'] == '手机号') {
                    $params['phone'] = $v['value'];
                }

                if (strpos($v['key'], '城市') !== false) {
                    $params['city'] = $v['value'];
                }

                if (strpos($v['key'], '金额') !== false) {
                    $params['apply_limit'] = $v['value'];
                }

                if (strpos($v['key'], '车') !== false) {
                    $params['pro_id'] = 4;
                }

                if (strpos($v['key'], '房') !== false) {
                    $params['pro_id'] = 3;
                }

                if (strpos($v['key'], '公积金') !== false) {
                    $params['pro_id'] = 6;
                }

                if (strpos($v['key'], '企业') !== false) {
                    $params['pro_id'] = 7;
                }

                $params['car'] = implode('|', $car);
                $params['house'] = implode('|', $house);
                $params['public_funds'] = implode('|', $public_funds);
                $params['company'] = implode('|', $company);
            }
        }
        $params['remark'] = json_encode($details, JSON_UNESCAPED_UNICODE);

        if ($this->is_check_repeat) {
            $isDayPhone = (new ClueModel())->isRepeatClue($params['phone'], $params['adv_id']);
            if ($isDayPhone) {
                ApiClueModel::setClueApiLogError($apiId, '线索已存在');
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索已存在', $params);
                return Json(['msg' => '线索已存在', 'status' => 200, "code" => 500]);
            }
        }

//        if ($this->is_check_repeat) {
            $isBlack = model('clue')->where(['phone' => $params['phone'], 'is_black' => 1])->find();
            if ($isBlack) {
                ApiClueModel::setClueApiLogError($apiId, '黑名单线索');
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '黑名单线索', $params);
                return Json(['msg' => '进线失败，黑名单线索', 'status' => 200, "code" => 500]);
            }
//        }

        // 城市
//        dump($params);
        $city_t[]=$params['city'];
        $params['apply_limit'] = htmlspecialchars_decode($params['apply_limit']);
//        dump($params);
        $city_info = clue_city_transform($city_t);
        if (!$city_info) {
            ApiClueModel::setClueApiLogError($apiId, '城市格式有误或未匹配到城市');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '未匹配到城市id', $params);
//            throw new ParamException(['msg'=>'线索接收失败，线索没有城市属性','errorCode'=>40001]);
            $params['city'] = '';
            $params['err_msg'] = '未匹配到城市id城市解析失败';
            //return Json(['msg' => '城市格式有误或未匹配到城市', 'status' => 200, "code" => 500]);
        } else {
            $province = Db::name('city')->where(['id' => $city_info['pid']])->find();
            $params['city'] = $province['id'] . '-' . $city_info['id'];
        }

        // 广告城市
        if (!empty($params['clue_city'])) {
            if (strpos($params['clue_city'], '|') !== false) {
                $clue_city_t = explode('|', $params['clue_city']);
            } elseif (strpos($params['clue_city'], '-') !== false) {
                $clue_city_t = explode('-', $params['clue_city']);
            } else {
                $clue_city_t = [$params['clue_city']];
            }
            $clue_city_info = clue_city_transform($clue_city_t);
            if (!$clue_city_info) {
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '广告城市 未匹配到城市id', $params);
            } else {
                $province = Db::name('city')->where(['id' => $clue_city_info['pid']])->find();
                $params['clue_city'] = $province['id'] . '-' . $clue_city_info['id'];
            }
        }

        if ($this->is_check_repeat) {
            //城市是否禁用
            $isCity = model('accountCity')->where(['acc_id' => $isAid['id'], 'city' => $params['city'], 'status' => 1])->find();
            if (!empty($isCity)) {
                ApiClueModel::setClueApiLogError($apiId, '账户城市已禁用');
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市已禁用', $post);
                //return Json(['msg' => '账户城市已禁用', 'status' => 200, "code" => 500]);
                return Json(['msg' => '线索已存在', 'status' => 200, "code" => 202]);
            }

            // 城市是否准入
            $is_allow = (new \app\common\model\Clue())->allowAccountCity($isAid['id'], $params['city']);
            if ($is_allow === false) {
                ApiClueModel::setClueApiLogError($apiId, '账户城市不准入');
                ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '账户城市不准入', $post);
                return Json(['msg' => '非需求城市', 'status' => 200, "code" => 500]);
            }
        }

        $clueCost = model('ClueAddCost')
            ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => $params['city']])
            ->where('status', 1)
            ->find();
        if (empty($clueCost)) {
            // 找不到城市就找默认全国城市
            $clueCost = model('ClueAddCost')
                ->where(['account_id' => $isAid['id'], 'pro_id' => $params['pro_id'], 'city' => ""])
                ->where('status', 1)
                ->find();
        }
        if (!empty($clueCost)) {
            $params['price'] = $clueCost['money'];
            $params['true_price'] = $clueCost['money'];
            $params['xz_price'] = $clueCost['money'];
            $params['xz_true_price'] = $clueCost['money'];
            $params['xz_price2'] = $clueCost['money'];
            $params['xz_true_price2'] = $clueCost['money'];
            $params['xz_price3'] = $clueCost['money'];
            $params['xz_true_price3'] = $clueCost['money'];
            $params['xz_price4'] = $clueCost['money'];
            $params['xz_true_price4'] = $clueCost['money'];
        } else {
            $params['price'] = $isAid['clue_cost'];
            $params['true_price'] = $isAid['clue_cost'];
            $params['xz_price'] = $isAid['clue_cost'];
            $params['xz_true_price'] = $isAid['clue_cost'];
            $params['xz_price2'] = $isAid['clue_cost'];
            $params['xz_true_price2'] = $isAid['clue_cost'];
            $params['xz_price3'] = $isAid['clue_cost'];
            $params['xz_true_price3'] = $isAid['clue_cost'];
            $params['xz_price4'] = $isAid['clue_cost'];
            $params['xz_true_price4'] = $isAid['clue_cost'];
        }
        $params['account_id'] = $isAid['id'];

        if(mb_strlen($params['apply_limit'])>=20){

            if (strpos($params['apply_limit'], '万') !== false) {
                preg_match_all('/\d+/', $params['apply_limit'], $matches);
                if(!empty($matches[0])){
                    $params['apply_limit'] = end($matches[0]).'万';
                }
            }else{
                preg_match_all('/\d+/', $params['apply_limit'], $matches);
                if(!empty($matches[0])){
                    $params['apply_limit'] = end($matches[0]);
                }
            }


        }

        //判断线索重复
//        $isClue = model('clue')->where(['phone' => $params['phone']])->find();

        // 1.记录线索
        $clueModel = new \app\common\model\Clue();
        $res = $clueModel->allowField(true)->save($params);

        if (empty($res)) {
            ApiClueModel::setClueApiLogError($apiId, '线索接收失败');
            ClueErrorLog::record($params['clue_id'] ?? time() . mt_rand(1000, 9999), '线索接收失败', $post);
            return Json(['msg' => '线索接收失败', 'status' => 200, "code" => 500]);
        }
        $id = $clueModel->id;

        Db::name('clue_api_log')->where('id', $apiId)->update(['status' => 1]);

        // 重复手机次数记录
//        if ($isClue) {
//            Db::name('clue_err_log')->insert(['type' => 1, 'phone' => $params['phone'], 'clue_id' => $id, 'adv_id' => $params['adv_id'], 'pro_id' => $params['pro_id'], 'city' => $params['city'], 'create_time' => time()]);
//        }

        /*if (empty($params['city'])) {
            return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 0]);
        }*/
        if (empty($params['city'])&&empty($params['clue_city'])) {
            return Json(['code' => 200, 'msg' => '线索接收成功,城市匹配失败：' . json_encode($res, JSON_UNESCAPED_UNICODE), 'message' => 'success']);
        }

        if (strpos($params['clue_name'], '测试') !== false) {
            return Json(['status' => 200, 'msg' => '测试线索接收成功', 'code' => 0]);
        }

        // 2.推送线索
//        $clue_info = $clueModel->find($id);
//
//        $res = $this->cluePush($clue_info, true);

        $jobHandlerClassName = 'app\job\ExprotClue@fire';
        // 2.当前任务归属的队列名称，如果为新队列，会自动创建
        $jobQueueName = "ExprotClue";

        $jobData = ['id' => $id];

        $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        return Json(['status' => 200, 'msg' => '线索接收成功', 'code' => 0]);
    }
}